package com.study.studyfive.file;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author zhangwei
 * @version 1.0
 * @date 2023/10/22 18:18
 */
@Slf4j
@RestController
public class FileController {
    private static final long MAX_FILE_SIZE = 5 * 1024 * 1024; // 最大文件大小为5MB

    /**
     * 支持上传附件，附件格式支持word、excel、pdf、ppt...，大小5M
     * @param file
     * @return
     * @throws Exception
     */

    @Value("${document.uploadPath}")
    private String uploadPath;

    @Value("${document.preview}")
    private String preview;


    /*上传文件*/
    @PostMapping("/upload")
    public String uploadFile(@RequestParam(name = "file",required = false) MultipartFile file) throws Exception {
        //Word文档/wps：Content-Type: application/vnd.openxmlformats-officedocument.wordprocessingml.document
        //Excel文档：Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
        //PDF文档：Content-Type: application/pdf
        //PPT文档：Content-Type: application/vnd.ms-powerpoint
        // wps的doc  application/msword
        // 微软的  application/vnd.ms-word

        List<String> fileTypeList = Arrays.asList("application/vnd.openxmlformats-officedocument.wordprocessingml.document",
                "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
                "application/pdf", "application/vnd.ms-powerpoint");


        log.info("文件内容类型："+file.getContentType());
        log.info("文件大小："+ file.getSize()/1024  + "KB" );
        log.info("文件上传名： " +file.getOriginalFilename());
        log.info("文件分隔符： "+File.separator);

        //处理文件上传
        if(file.isEmpty()) {
            throw new Exception("文件大小为空");
        }
        //文件最大不超过5M
        if (file.getSize() >  MAX_FILE_SIZE) {
            throw new Exception("文件过大，请上传5M以内的文件");
        }
        //校验文件格式
        String contentType = file.getContentType();
        if (!fileTypeList.contains(contentType)) {
            throw new Exception("文件格式包括word、excel、pdf、ppt");
        }
        String fileName = file.getOriginalFilename();
        String  fileExtension = fileName.substring(fileName.lastIndexOf(".") );

        String  uploadFileName =  uploadPath + UUID.randomUUID().toString()  + fileExtension;
        log.info("文件上传的路径： " +uploadFileName);
        File file1 = new File(uploadPath);
        if (!file1.exists()) {
            file1.mkdirs();
        }
        //上传文件
        file.transferTo(new File(uploadFileName));
        return uploadFileName;
    }



    /*上传多个文件*/
    @PostMapping("/uploadFiles")
    public List<String> uploadFiles(@RequestParam(name = "files",required = false) MultipartFile[] files) throws Exception {
        //Word文档/wps：Content-Type: application/vnd.openxmlformats-officedocument.wordprocessingml.document
        //Excel文档：Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
        //PDF文档：Content-Type: application/pdf
        //PPT文档：Content-Type: application/vnd.ms-powerpoint
        // wps的doc  application/msword
        // 微软的  application/vnd.ms-word

        List<String> fileTypeList = Arrays.asList("application/vnd.openxmlformats-officedocument.wordprocessingml.document",
                "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
                "application/pdf", "application/vnd.ms-powerpoint");

       // StringBuilder  fileStr = new StringBuilder();
        ArrayList<String> arrayList = new ArrayList<>();
        for (MultipartFile file : files) {

            log.info("文件内容类型："+file.getContentType());
            log.info("文件大小："+ file.getSize()/1024  + "KB" );
            log.info("文件上传名： " +file.getOriginalFilename());
            log.info("文件分隔符： "+File.separator);

            //处理文件上传
            if(file.isEmpty()) {
                throw new Exception("文件大小为空");
            }
            //文件最大不超过5M
            if (file.getSize() >  MAX_FILE_SIZE) {
                throw new Exception("文件过大，请上传5M以内的文件");
            }
            //校验文件格式
          /*  String contentType = file.getContentType();
            if (!fileTypeList.contains(contentType)) {
                throw new Exception("文件格式包括word、excel、pdf、ppt");
            }*/
            String fileName = file.getOriginalFilename();
            String  fileExtension = fileName.substring(fileName.lastIndexOf(".") );
            // 获取当前日期
            Date currentDate = new Date();

            // 定义日期格式
            SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");

            // 格式化日期  年月日
            String formattedDate = formatter.format(currentDate);

            //明细id
            String  m_id = "BA2561";
            String separator = File.separator;

            File file1 = new File(uploadPath + formattedDate + separator + m_id);
            if (!file1.exists()) {
                file1.mkdirs();
            }

            String  uploadFileName =  uploadPath + formattedDate + separator + m_id + separator + UUID.randomUUID() +fileExtension;
            log.info("文件上传的路径： " +uploadFileName);
            File uploadFile = new File(uploadFileName);
            //拼接文件地址
            arrayList.add(uploadFileName);
            //fileStr.append(uploadFileName).append(",");
            //上传文件
            file.transferTo(uploadFile);
        }
        //fileStr.deleteCharAt(fileStr.length()-1);
        return arrayList;
    }


    /*
      下载文件
     */
    @PostMapping("/download")
    public HttpServletResponse download(String path, HttpServletResponse response) {
        try {
            // path是指欲下载的文件的路径。
            path = preview+ path;
            File file = new File( path);
            // 取得文件名。
            String filename = file.getName();
            // 以流的形式下载文件。
            InputStream fis = new BufferedInputStream(new FileInputStream(path));
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();
            // 清空response
            response.reset();
            // 设置response的Header
            response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes()));
            response.addHeader("Content-Length", "" + file.length());
            OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/octet-stream");
            toClient.write(buffer);
            toClient.flush();
            toClient.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        return response;
    }

}
